"use client";

import { useMemo, useState } from "react";
import { useAgents, useEnvironmentTree, useEvents, useLedgerSnapshot, useTasks, useTimeline } from "../lib/api";
import {
  agents as mockAgents,
  environment as mockEnvironment,
  events as mockEvents,
  ledgerSnapshot as mockLedger,
  tasks as mockTasks,
  timeline as mockTimeline
} from "../lib/mock";
import { AgentNavigator } from "./agent-navigator";
import { MainVisualization } from "./main-visualization";
import { MetricsRail } from "./metrics-rail";
import { CommandConsole } from "./command-console";
import { useCommandPalette } from "../lib/command-palette";
import { useAuth } from "../lib/auth";

export function Dashboard() {
  const {
    data: agentData = mockAgents,
    error: agentError
  } = useAgents(mockAgents);
  const {
    data: ledgerData = mockLedger,
    error: ledgerError
  } = useLedgerSnapshot(mockLedger);
  const {
    data: eventData = mockEvents,
    error: eventError
  } = useEvents(mockEvents);
  const {
    data: taskData = mockTasks,
    error: taskError
  } = useTasks(mockTasks);
  const {
    data: timelineData = mockTimeline,
    error: timelineError
  } = useTimeline(mockTimeline);
  const { data: environmentData = mockEnvironment, error: environmentError } = useEnvironmentTree(5, mockEnvironment);
  const [selected, setSelected] = useState<string | undefined>(agentData[0]?.id);
  const palette = useCommandPalette();
  const auth = useAuth();

  const selectedAgent = useMemo(() => agentData.find(agent => agent.id === selected), [agentData, selected]);

  return (
    <>
      <CommandConsole {...palette} agents={agentData} roles={auth.roles} />
      <main className="grid min-h-screen gap-4 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 p-6 text-slate-100 sm:grid-cols-[280px_minmax(0,1fr)_300px] sm:grid-rows-[auto] sm:p-8">
        <AgentNavigator agents={agentData} selected={selectedAgent?.id} onSelect={setSelected} />
        <section className="flex flex-col gap-4 overflow-hidden">
          <header className="surface-panel flex flex-wrap items-center justify-between gap-4 rounded-xl p-4 shadow-xl">
            <div>
              <h1 className="text-2xl font-semibold text-slate-100">Agent-Society Control Center</h1>
              <p className="text-sm text-slate-400">
                Observe compute flows, governance state, and experiment readiness in real time.
              </p>
            </div>
            <div className="flex items-center gap-2 text-sm text-slate-400">
              {(agentError || ledgerError || eventError || taskError || environmentError || timelineError) && (
                <span className="rounded-full border border-rose-600/60 bg-rose-500/10 px-3 py-1 text-rose-200">
                  API unavailable – showing cached data
                </span>
              )}
              <button
                type="button"
                onClick={palette.openPalette}
                className="rounded-full border border-slate-700/60 bg-slate-900/60 px-3 py-1 hover:border-sky-500/60 hover:text-sky-200"
              >
                ⌘K Command Console
              </button>
              <span className="rounded-full border border-sky-600/60 bg-sky-500/10 px-3 py-1 text-sky-200">Live
                data (fallback to mock)</span>
            </div>
          </header>
          <MainVisualization
            agents={agentData}
            ledger={ledgerData}
            events={eventData}
            tasks={taskData}
            environment={environmentData}
            timeline={timelineData}
          />
        </section>
        <MetricsRail ledger={ledgerData} />
      </main>
    </>
  );
}

export default Dashboard;
